import { MciNotification, MciMessageBox, MciMessage, MciLabel, MciButton } from '@/components/base';
import { GraphContainer } from '@/components/business/GraphContainer';
import { Template } from '@/components/business/Template';
import { useGraph } from '@/hooks/useGraph';
import { useRole } from '@/hooks/useRole';
import { formatConditions } from '@/utils/edge-process';
// import FlowTools from '@/views/decision-flow/components/FlowTools';
import { FlowOperation } from '../FlowOperation';
import { AssignFlowWeight } from '../AssignFlowWeight';
import './index.scss';
import { decisionKey } from '../../types';
import { ElIcon, ElPopover, ElText, ElDialog, ElTooltip } from 'element-plus';
import { InfoFilled } from '@element-plus/icons-vue';
import {
  IGetDecisionFlowGetRes,
  getDecisionFlowGet,
  postDecisionFlowListByVersion,
  postDecisionFlowNewVersion,
  postDecisionFlowWeightAssign
} from '@/api';

export const FlowContent = defineComponent({
  props: {
    flowVersionList: {
      type: Array,
      default: () => ([])
    }
  },
  emits: ['delete'],
  setup(props, { emit, expose }) {
    const { graph, updateInteractingState } = useGraph();
    const route = useRoute();
    const router = useRouter();
    const flowId = computed(() => {
      return route.query.flowId as string;
    });
    const decisionId = computed(() => {
      return route.query.decisionId as string;
    });
    const flowDetail = ref({} as IGetDecisionFlowGetRes);
    const flowList = ref([]);
    const allowSetWeight = ref(false);
    const setWeightDialog = ref(false);
    // 查看详情
    const openFlowDetail = ref({});
    const { importData, setImportJSON } = inject(decisionKey);

    // const flowTabs = [
    //   {
    //     label: '设计',
    //     name: 'flowDesign'
    //   },
    //   {
    //     label: '配置',
    //     name: 'flowConfig'
    //   }
    // ];
    // const activeTab = ref('flowDesign');

    /* 获取策略配置岗的场景分类权限 */
    const categoryId = computed(() => {
      return route.query.categoryId as string;
    });
    const permissionerObj = ref<object>({});

    const setDetail = (data: IGetDecisionFlowGetRes) => {
      if (!data) return;
      try {
        if (data.graph) {
          graph.value?.fromJSON(JSON.parse(data.graph!));
          graph.value && updateEdge();
          setTimeout(() => {
            graph.value?.centerContent();
          });
        } else {
          graph.value?.clearCells();
        }
      } catch (error) {
        MciNotification.error({
          message: '流程图数据异常',
          position: 'bottom-right'
        });
      }
    };

    const setPermission = async () => {
      if (flowId.value) {
        // activeTab.value = 'flowDesign';
        const { permissionerRole, initFlowDisabled } = useRole(null, categoryId.value as string);
        await initFlowDisabled();
        permissionerObj.value = permissionerRole.value;
        if (!(flowDetail.value.status === 0 && permissionerObj.value?.configRole)) {
          updateInteractingState(false);
        } else {
          updateInteractingState(true);
        }
      }
    };

    const getDetail = async () => {
      if (!flowId.value) return;
      const data = await getDecisionFlowGet({ flowId: flowId.value });
      flowDetail.value = data || {};
      setDetail(data);
    };

    const getListByVersion = async (refresh: boolean = false) => {
      if(props.flowVersionList && props.flowVersionList.length !== 0 && !refresh) {
        flowList.value = props.flowVersionList;
      } else if (decisionId.value){
        const data = await postDecisionFlowListByVersion({ decisionId: decisionId.value });
        flowList.value = data;
      }
      if (flowList.value && flowList.value.length !== 0) {
        allowSetWeight.value = flowList.value.some((item) => item.status === 2);
      } else {
        allowSetWeight.value = false;
      }
    };

    const getNewListByVersion = async () => {
      if (!decisionId.value) return;
      const data = await postDecisionFlowListByVersion({ decisionId: decisionId.value });
      if (data.length === 0) return;
      flowList.value = data;
      const detailList = data.filter(item => item.status === 0 || item.status === 1);
      const newList = detailList.length > 0 ? detailList : data;
      const detailObj = newList[0];
      const detail = {
        flowId: detailObj.id,
        decisionId: detailObj.decisionId,
        categoryId: detailObj.categoryId,
      };
      router.push({
        name: 'DecisionFlow',
        query: detail
      });
    };

    const updateEdge = () => {
      graph.value?.getEdges().forEach((edge) => {
        const assignmentList = edge.getData().condition as any[];
        let strList: string[] = [];
        if (assignmentList && assignmentList.length !== 0) {
          assignmentList.forEach((assignment) => {
            const formattedConditions = formatConditions(assignment.conditions.conditions, assignment.conditions.conjs);
            formattedConditions && strList.push(formattedConditions);
          });
          if (strList.length !== 0) {
            edge.setLabels([
              {
                attrs: {
                  label: { text: strList.join('\n\n') },
                  text: {
                    fill: 'var(--color-blue-6)',
                    fontSize: 12,
                    textAnchor: 'middle',
                    textVerticalAnchor: 'middle'
                  },
                  rect: {
                    ref: 'label',
                    fill: 'var(--color-blue-1)',
                    stroke: 'var(--color-blue-4)',
                    refWidth: 14,
                    refHeight: 5,
                    refX: -7,
                    refY: -2.5,
                    rx: 20,
                    ry: 20
                  }
                },
                position: {
                  distance: 0.5
                }
              }
            ]);
          } else {
            edge.setLabels([]);
          }
        } else {
          edge.setLabels([]);
        }
      });
    };

    // 新增版本
    const createVersion = async (itemFlowId: string, versionNo: string) => {
      MciMessageBox.confirm(`是否以 ${versionNo}为基础生成该决策流新的版本`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        const filterStatus = flowList.value.some(item => (item.status === 0 || item.status === 1));
        if(filterStatus) {
          MciMessage({
            message: '该决策流已经存在未发布的版本，不能新增',
            type: 'warning'
          });
          return;
        } else {
          postDecisionFlowNewVersion({ flowId: itemFlowId }).then((res) => {
            MciMessage({
              message: '新增成功',
              type: 'success'
            });
            router.push({
              name: 'DecisionFlow',
              query: { flowId: res.id, decisionId: res.decisionId, categoryId: res.categoryId }
            });
            getListByVersion(true);
          });
        }
      });
    };

    // 查看明细
    const showDetail = async (row: object) => {
      if (!row?.id) return;
      openFlowDetail.value = row;

      updateInteractingState(false);

      const res = await getDecisionFlowGet({ flowId: row.id! });
      setDetail(res);
    };

    // 恢复版本
    // const recoverVersion = async (flowVersion: any) => {
    //   console.log('🚀 ~ recoverVersion ~ id:', flowVersion, flowDetail.value.status);
    //   if (flowDetail.value.status === 0) {
    //     MciMessageBox.confirm('是否将选择的版本覆盖到当前决策流？', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消'
    //     }).then(async () => {
    //       console.log('postDecisionFlowWeightAssign 未审批', flowList.value);
    //       const flowWeights = flowList.value.map(item => {
    //         const weightCount = item.id === flowVersion?.id ? 100 : 0;
    //         return {
    //           ...item,
    //           weight: weightCount
    //         }
    //       });
    //       const data = await postDecisionFlowWeightAssign({ flowWeights });
    //       router.push({
    //         name: 'DecisionFlow',
    //         query: { flowId: flowVersion?.id, decisionId: flowVersion?.decisionId, categoryId: flowVersion?.categoryId }
    //       });
    //       getListByVersion(true);
    //     });
    //   } else if (flowDetail.value.status === 1) {
    //     MciMessageBox.confirm('当前决策流版本状态为审批中，不能恢复，请先驳回审批流。', '提示', {
    //       showCancelButton: false,
    //       showConfirmButton: false
    //     });
    //   } else if (flowDetail.value.status === 2) {
    //     MciMessageBox.confirm('是否按选择的版本生成该决策流新的版本？', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消'
    //     }).then(async () => {
    //       console.log('postDecisionFlowNewVersion 已发布');
    //       const data = await postDecisionFlowNewVersion({ flowId: flowVersion?.id });
    //       MciMessage({
    //         message: '新增成功',
    //         type: 'success'
    //       });
    //       router.push({
    //         name: 'DecisionFlow',
    //         query: { flowId: data?.id, decisionId: data?.decisionId, categoryId: data?.categoryId }
    //       });
    //       getListByVersion(true);
    //     });
    //   }
    // };

    const statusTitle = (status: number) => {
      switch (status) {
        case 0:
          return '待审批';
        case 1:
          return '审核中';
        case 2:
          return '已发布';
        case 3:
          return '已下线';
        default:
          break;
      }
    };

    // 保存配置加载
    // const loading = ref(false);
    // const flowConfigRef = ref();
    // 保存配置
    // const saveHandle = async () => {
    //   loading.value = true;
    //   flowConfigRef.value && flowConfigRef.value.saveData();
    // };

    watch(
      [flowId, () => importData.flowId],
      ([newFlowId, newImportFlowId], [oldFlowId]) => {
        // 切换决策
        if (oldFlowId !== newFlowId) {
          getDetail();
          getListByVersion(false);
          setPermission();
        }
        // 导入决策
        if (newImportFlowId && newFlowId === newImportFlowId) {
          MciMessageBox.confirm('是否确定导入？该决策都将会被替换。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            setDetail({ ...importData.importJSON });
            setPermission();
            setImportJSON('', null);
          });
        }
      },
      { immediate: true }
    );

    const refreshDetail = () => {
      getDetail();
      getListByVersion(true);
      setPermission();
    };

    expose({
      refresh: refreshDetail
    });

    return () => {
      return (
        <div class="w-full flow-content bg-white bd-l">
          {!openFlowDetail.value?.id && (
            <div class="flex-1 flex flex-col h-full">
              <div class="flex justify-between items-center">
                <div class="my-8px mx-16px py-16 pl-8 flex items-center justify-left rounded-8px">
                  <MciLabel>{flowDetail.value.flowName}</MciLabel>
                  <ElText tag="b">
                    {flowDetail.value.flowDesc && (
                      <ElPopover trigger={'hover'} placement={'right'} width={'30%'}>
                        {{
                          reference() {
                            return (
                              <>
                                <ElIcon>
                                  <InfoFilled />
                                </ElIcon>
                              </>
                            );
                          },
                          default() {
                            return (
                              <>
                                {flowDetail.value.flowDesc &&
                                flowDetail.value.flowDesc.split('\n') &&
                                flowDetail.value.flowDesc.split('\n').length > 1 ? (
                                  <div>
                                    {flowDetail.value.flowDesc.split('\n').map((item) => {
                                      return (
                                        <div class="py-1">
                                          <ElText>{item}</ElText>
                                        </div>
                                      );
                                    })}
                                  </div>
                                ) : (
                                  <ElText>{flowDetail.value.flowDesc}</ElText>
                                )}
                              </>
                            );
                          }
                        }}
                      </ElPopover>
                    )}
                  </ElText>
                  <div class="flex items-center ml-8">
                    <span class="mr-8">版本：</span>
                    <ElPopover placement={'bottom'} width={230} trigger={'hover'}>
                      {{
                        reference: () => {
                          return (
                            <MciButton type={'primary'} link={true}>
                              {flowDetail.value.versionNo + '（当前版本）' + '（' + statusTitle(flowDetail.value.status) + '）'}
                            </MciButton>
                          );
                        },
                        default: () => {
                          const getFlowItemClass = (index) => {
                            return `flex items-center ${index + 1 === flowList.value.length ? '' : 'mb-8'}`;
                          };
                        
                          const renderFlowItemsAndGrayScaleButton = () => {
                            return [
                              ...flowList.value.map((item, index) => {
                                const renderItem = renderFlowItem(item, index);
                                if (item.id !== flowId.value) {
                                  return renderItem;
                                } else {
                                  return null;
                                }
                              }),
                              <div class="flex items-center">
                                <MciButton
                                  type="primary"
                                  icon="mci-icon-add"
                                  style={{ color: 'var(--color-brand-6)', fontSize: '16px', marginLeft: '-4px' }}
                                  link
                                  onClick={() => createVersion(flowId.value, flowDetail.value.versionNo)}
                                >
                                  新增版本
                                </MciButton>
                                <ElTooltip placement="top" content="为已发布版本配置灰度">
                                  <MciButton
                                    type="primary"
                                    icon="mci-icon-setting"
                                    style={{ color: 'var(--color-brand-6)', fontSize: '16px', marginLeft: '8px' }}
                                    link
                                    disabled={!allowSetWeight.value}
                                    onClick={() => setWeightDialog.value = true}
                                  >
                                    灰度设置
                                  </MciButton> 
                                </ElTooltip>
                              </div>,
                            ];
                          };
                        
                          const renderFlowItem = (item, index) => {
                            return (
                              <div class={getFlowItemClass(index)}>
                                <span>{`${item.versionNo}（${statusTitle(item.status)}）`}</span>
                                <MciButton
                                  type="primary"
                                  class="ml-8"
                                  style={{ color: 'var(--color-brand-6)' }}
                                  link
                                  onClick={() => showDetail(item)}
                                >
                                  查看
                                </MciButton>
                                {
                                  flowDetail.value.status === 2 && item.status === 2 && (
                                    <ElTooltip placement="top" content="基于该版本生成该决策流新的版本">
                                      <MciButton
                                        type="primary"
                                        class="ml-8"
                                        style={{ color: 'var(--color-brand-6)' }}
                                        link
                                        onClick={() => createVersion(item.id, item.versionNo)}
                                      >
                                        新增版本
                                      </MciButton>
                                    </ElTooltip>
                                  )
                                }
                              </div>
                            );
                          };
                        
                          return <div>{renderFlowItemsAndGrayScaleButton()}</div>;
                        },
                      }}
                    </ElPopover>
                  </div>
                </div>
                {/* <MciTabs v-model={activeTab.value} tabs={flowTabs} type={'normal-theme'} class="ml-16" /> */}
                {/* <FlowTools /> */}
                  <FlowOperation
                    flowDetail={flowDetail.value}
                    onDelete={() => emit('delete')}
                    onRefresh={() => {
                      getDetail();
                      getListByVersion(true);
                    }}
                    permissionRoles={permissionerObj.value}
                  />
                {/* {activeTab.value === 'flowConfig' && (
                  <MciButton class="mr-16" loading={loading.value} type="info" onClick={saveHandle}>
                    保存
                  </MciButton>
                )} */}
              </div>
              {/* {activeTab.value === 'flowDesign' && (
                <div class="my-8px mx-16px py-16 pl-8 flex items-center justify-left bg-fill-2 rounded-8px">
                  <MciLabel>{flowDetail.value.flowName}</MciLabel>
                  <ElText tag="b">
                    {flowDetail.value.flowDesc && (
                      <ElPopover trigger={'hover'} placement={'right'} width={'30%'}>
                        {{
                          reference() {
                            return (
                              <>
                                <ElIcon>
                                  <InfoFilled />
                                </ElIcon>
                              </>
                            );
                          },
                          default() {
                            return (
                              <>
                                {flowDetail.value.flowDesc &&
                                flowDetail.value.flowDesc.split('\n') &&
                                flowDetail.value.flowDesc.split('\n').length > 1 ? (
                                  <div>
                                    {flowDetail.value.flowDesc.split('\n').map((item) => {
                                      return (
                                        <div class="py-1">
                                          <ElText>{item}</ElText>
                                        </div>
                                      );
                                    })}
                                  </div>
                                ) : (
                                  <ElText>{flowDetail.value.flowDesc}</ElText>
                                )}
                              </>
                            );
                          }
                        }}
                      </ElPopover>
                    )}
                  </ElText>
                </div>
              )} */}
              {/* {activeTab.value === 'flowDesign' && ( */}
                <div class="flex flex-col grow w-full">
                  {/* <FlowTools /> */}
                  <Template graph={graph.value as any} />
                  <GraphContainer
                    flowState={flowDetail.value.status === 0 && permissionerObj.value?.configRole ? 'edit' : 'view'}
                    class="flex-1"
                  />
                </div>
              {/* )} */}
              {/* {activeTab.value === 'flowConfig' && (
                <div class="flex flex-col w-full bg-gray-50 rounded-8px">
                  <FlowConfig
                    ref={flowConfigRef}
                    flowId={flowId.value}
                    onChange={(isLoading: boolean) => {
                      loading.value = isLoading;
                    }}
                  />
                </div>
              )} */}
            </div>
          )}
          {!!openFlowDetail.value?.id && (
            <ElDialog
              destroy-on-close
              append-to-body
              fullscreen
              class="flow-version-detail-dialog"
              title={openFlowDetail.value.flowName}
              modelValue={!!openFlowDetail.value?.id}
              onClose={() => {
                openFlowDetail.value = {};
                refreshDetail();
              }}>
              <GraphContainer flowState={'view'} class="w-full h-screen" />
            </ElDialog>
          )}
          {setWeightDialog.value && (
            <AssignFlowWeight
              flowList={flowList.value}
              onRefresh={() => {
                getNewListByVersion();
              }}
              onUpdate:modelValue={(val) => {
                setWeightDialog.value = val;
              }}
            />
          )}
        </div>
      );
    };
  }
});
